package fr.mathis.tourhanoipro;

import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.internal.nineoldandroids.animation.Animator;
import com.actionbarsherlock.internal.nineoldandroids.animation.Animator.AnimatorListener;
import com.actionbarsherlock.internal.nineoldandroids.animation.ObjectAnimator;
import com.actionbarsherlock.internal.nineoldandroids.animation.ValueAnimator;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.example.games.basegameutils.BaseGameActivity;

import fr.mathis.tourhanoipro.interfaces.HelpListener;
import fr.mathis.tourhanoipro.interfaces.TurnListener;
import fr.mathis.tourhanoipro.tools.DataManager;
import fr.mathis.tourhanoipro.tools.Tools;
import fr.mathis.tourhanoipro.views.GameView;

public class MainActivity extends BaseGameActivity implements TurnListener {

	static final int MENU_QUICK_TOUCH = 1;
	static final int MENU_DECONNECT = 2;
	static final int MENU_RIGHT_DRAWER = 3;

	static final int POPUP_MENU_PLAY = 0;
	static final int POPUP_MENU_DELETE = 1;

	static final int RESULT_RESOLVER = 4;
	static final int RESULT_CONGRATS = 0;
	static final int RESULT_ACHIVEMENTS = 1;
	static final int RESULT_LEADERBOARDS = 2;

	DrawerLayout mDrawerLayout;
	ActionBarDrawerToggle mDrawerToggle;
	View leftDrawer;
	View rightDrawer;
	boolean isSlideLock = false;
	GameView currentGame;

	MenuItem menuItemDeconnection;
	MenuItem menuItemSmallTouch;
	MenuItem openRightDrawer;
	int nextIconForSmallTouchMenu = -1;
	boolean showMenu = true;
	String actionBarSubtitle = null;
	int currentGameIndex = 0;
	ArrayList<String> allGames;
	ListView lv;
	GameAdapter adapter;
	boolean wantstoShowHelp;

	boolean spinnerCreatedShouldAvoidFirstItemSelection = true;

	public MainActivity() {
		super(BaseGameActivity.CLIENT_APPSTATE | BaseGameActivity.CLIENT_GAMES);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getSupportActionBar().setIcon(R.drawable.ic_launcher_white);

		currentGame = (GameView) findViewById(R.id.gameView1);
		allGames = DataManager.GetAllSavedGames(getApplicationContext());

		initDrawer();
		initEvents();
		initSpinner();
		initListView();

		if (!DataManager.GetMemorizedValueBoolean("showTutoFirstTime2", getApplicationContext())) {
			DataManager.MemorizeValue("showTutoFirstTime2", true, getApplicationContext());
			showTutorial();
		}

		isSlideLock = DataManager.GetMemorizedValueBoolean("lock", getApplicationContext());
	}

	private void initListView() {
		lv = (ListView) findViewById(R.id.lvSavedGames);
		adapter = new GameAdapter(LayoutInflater.from(this));
		lv.setAdapter(adapter);

		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

			}
		});
	}

	private void initDrawer() {
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		if (findViewById(R.id.isTablet) == null) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}

		if (findViewById(R.id.drawer_layout) != null) {
			mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
			leftDrawer = findViewById(R.id.left_drawer);
			rightDrawer = findViewById(R.id.right_drawer);

			showClosedIcon();
			mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
				public void onDrawerClosed(View view) {
					showClosedIcon();
				}

				public void onDrawerOpened(View drawerView) {
					showOpenedIcon();
					if (drawerView == rightDrawer) {
						DataManager.MemorizeValue("discoveredRightDrawer", true, getApplicationContext());
						findViewById(R.id.v_swype_indicator).setVisibility(View.GONE);
					}
				}

				@Override
				public void onDrawerSlide(View drawerView, float slideOffset) {
					if (drawerView == leftDrawer)
						super.onDrawerSlide(drawerView, slideOffset);
				}
			};
			mDrawerLayout.setDrawerListener(mDrawerToggle);

		}
	}

	private void initEvents() {
		findViewById(R.id.btn_newGame).setOnClickListener(new OnClickListener() {
			@SuppressLint("NewApi")
			@Override
			public void onClick(View v) {
				restartGame();
				closeDrawer();

				if (!isSlideLock && !DataManager.GetMemorizedValueBoolean("discoveredRightDrawer", getApplicationContext())) {
					if (findViewById(R.id.v_swype_indicator) != null) {
						findViewById(R.id.v_swype_indicator).setVisibility(View.VISIBLE);
						ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(findViewById(R.id.v_swype_indicator), "alpha", 0.0f, 0.75f);
						alphaAnimator.setDuration(1000);
						alphaAnimator.setRepeatCount(ValueAnimator.INFINITE);
						alphaAnimator.setRepeatMode(ValueAnimator.REVERSE);
						alphaAnimator.start();
					}
				}
			}
		});

		findViewById(R.id.btn_tutorial).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showTutorial();
				DataManager.MemorizeValue("helpCompleted", false, getApplicationContext());
				DataManager.MemorizeValue("discoveredRightDrawer", false, getApplicationContext());
			}
		});

		findViewById(R.id.sign_in_button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				beginUserInitiatedSignIn();
			}
		});

		findViewById(R.id.btn_achievement).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (getGamesClient().isConnected()) {
					startActivityForResult(getGamesClient().getAchievementsIntent(), RESULT_ACHIVEMENTS);
				}
			}
		});

		findViewById(R.id.btn_leaderboard).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (getGamesClient().isConnected()) {
					startActivityForResult(getGamesClient().getAllLeaderboardsIntent(), RESULT_LEADERBOARDS);
				}
			}
		});

		if (findViewById(R.id.iv_drawerLock) != null) {

			ImageView ivDrawerLock = (ImageView) findViewById(R.id.iv_drawerLock);

			ivDrawerLock.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					isSlideLock = !isSlideLock;
					DataManager.MemorizeValue("lock", isSlideLock, getApplicationContext());
					((ImageView) v).setImageResource(isSlideLock ? R.drawable.ic_drawer_unlocked : R.drawable.ic_drawer_locked);

					if (isSlideLock && mDrawerLayout != null)
						mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
					if (mDrawerLayout != null)
						mDrawerLayout.closeDrawers();
					supportInvalidateOptionsMenu();
				}
			});

			ivDrawerLock.setOnLongClickListener(new OnLongClickListener() {
				@Override
				public boolean onLongClick(View v) {
					Toast.makeText(getApplicationContext(), R.string.s71, Toast.LENGTH_SHORT).show();

					return true;
				}
			});

			ivDrawerLock.setImageResource(isSlideLock ? R.drawable.ic_drawer_unlocked : R.drawable.ic_drawer_locked);
		}

		currentGame.setTurnListener(this);
	}

	private void initSpinner() {
		Spinner spinner = (Spinner) findViewById(R.id.spinnerCircles);
		ArrayAdapter<CharSequence> choices = ArrayAdapter.createFromResource(this, R.array.circles, R.layout.spinner_item);
		spinner.setAdapter(choices);

		int currentNumberOfCircle = -1;
		int spinnerPosition = -1;

		SharedPreferences mgr = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
		currentNumberOfCircle = Integer.parseInt(mgr.getString("nbCircles", "5"));

		String[] circles = getResources().getStringArray(R.array.circles);
		for (int i = 0; i < circles.length; i++) {
			if (currentNumberOfCircle == Integer.parseInt(circles[i])) {
				spinnerPosition = i;
				break;
			}
		}

		spinner.setSelection(spinnerPosition);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@SuppressLint("NewApi")
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				if (!spinnerCreatedShouldAvoidFirstItemSelection) {
					String[] circles = getResources().getStringArray(R.array.circles);
					int nbOfDisks = Integer.parseInt(circles[arg2]);

					SharedPreferences mgr = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
					SharedPreferences.Editor editor = mgr.edit();
					editor.putString("nbCircles", nbOfDisks + "");
					editor.commit();

					allGames.set(currentGameIndex, currentGame.saveGameAsString());
					currentGame.createNewGame();
					allGames.add(0, currentGame.saveGameAsString());

					DataManager.SaveAllGames(allGames, getApplicationContext());
					allGames = DataManager.GetAllSavedGames(getApplicationContext());

					adapter.notifyDataSetChanged();
					closeDrawer();

					if (!isSlideLock && !DataManager.GetMemorizedValueBoolean("discoveredRightDrawer", getApplicationContext())) {
						if (findViewById(R.id.v_swype_indicator) != null) {
							findViewById(R.id.v_swype_indicator).setVisibility(View.VISIBLE);
							ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(findViewById(R.id.v_swype_indicator), "alpha", 0.0f, 0.75f);
							alphaAnimator.setDuration(1000);
							alphaAnimator.setRepeatCount(ValueAnimator.INFINITE);
							alphaAnimator.setRepeatMode(ValueAnimator.REVERSE);
							alphaAnimator.start();
						}
					}
				} else {
					spinnerCreatedShouldAvoidFirstItemSelection = false;
				}

			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
	}

	@SuppressLint("NewApi")
	private void initHelpPopup(boolean show) {
		wantstoShowHelp = false;
		if (show) {
			if (!DataManager.GetMemorizedValueBoolean("helpCompleted", getApplicationContext())) {

				final View stepContainer = findViewById(R.id.rl_help);
				final View step0 = findViewById(R.id.ll_help_step0);
				final View step1 = findViewById(R.id.ll_help_step1);
				final View step2 = findViewById(R.id.ll_help_step2);

				stepContainer.setVisibility(View.VISIBLE);
				step0.setVisibility(View.VISIBLE);
				step1.setVisibility(View.GONE);
				step2.setVisibility(View.GONE);

				ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(stepContainer, "alpha", 0.0f, 1.0f);
				alphaAnimator.setDuration(500);
				alphaAnimator.start();

				step0.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						wantstoShowHelp = true;
						ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(stepContainer, "alpha", 1.0f, 0.0f);
						alphaAnimator.setDuration(500);
						alphaAnimator.addListener(new AnimatorListener() {

							@Override
							public void onAnimationStart(Animator animation) {
							}

							@Override
							public void onAnimationRepeat(Animator animation) {
							}

							@Override
							public void onAnimationEnd(Animator animation) {
								step0.setVisibility(View.GONE);
								step1.setVisibility(View.VISIBLE);
								step2.setVisibility(View.GONE);
								ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(stepContainer, "alpha", 0.0f, 1.0f);
								alphaAnimator.setDuration(500);
								alphaAnimator.start();
								MainActivity.this.currentGame.drawHelpLine(true);
							}

							@Override
							public void onAnimationCancel(Animator animation) {
							}
						});
						alphaAnimator.start();

					}
				});

				currentGame.setHelpListener(new HelpListener() {

					@Override
					public void stepPassed(int step) {

						if (step == 0 && wantstoShowHelp) {
							ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(stepContainer, "alpha", 1.0f, 0.0f);
							alphaAnimator.setDuration(500);
							alphaAnimator.addListener(new AnimatorListener() {

								@Override
								public void onAnimationStart(Animator animation) {
								}

								@Override
								public void onAnimationRepeat(Animator animation) {
								}

								@Override
								public void onAnimationEnd(Animator animation) {
									step0.setVisibility(View.GONE);
									step1.setVisibility(View.GONE);
									step2.setVisibility(View.VISIBLE);
									ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(stepContainer, "alpha", 0.0f, 1.0f);
									alphaAnimator.setDuration(500);
									alphaAnimator.start();
								}

								@Override
								public void onAnimationCancel(Animator animation) {
								}
							});
							alphaAnimator.start();
						} else {
							if (wantstoShowHelp) {
								DataManager.MemorizeValue("helpCompleted", true, getApplicationContext());
							}

							ObjectAnimator alphaAnimator = ObjectAnimator.ofFloat(stepContainer, "alpha", 1.0f, 0.0f);
							alphaAnimator.setDuration(500);
							alphaAnimator.addListener(new AnimatorListener() {

								@Override
								public void onAnimationStart(Animator animation) {
								}

								@Override
								public void onAnimationRepeat(Animator animation) {
								}

								@Override
								public void onAnimationEnd(Animator animation) {
									step0.setVisibility(View.GONE);
									step1.setVisibility(View.GONE);
									step2.setVisibility(View.GONE);
									stepContainer.setVisibility(View.GONE);
								}

								@Override
								public void onAnimationCancel(Animator animation) {
								}
							});
							alphaAnimator.start();
						}
					}

				});
			}
		} else {
			final View stepContainer = findViewById(R.id.rl_help);
			stepContainer.setVisibility(View.GONE);
		}

	}

	private void showClosedIcon() {
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH && findViewById(R.id.isTablet) == null) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}
		showMenu = true;
		supportInvalidateOptionsMenu();
		if (isSlideLock && mDrawerLayout != null)
			mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		getSupportActionBar().setSubtitle(actionBarSubtitle);
		if (mDrawerToggle != null)
			mDrawerToggle.syncState();
		currentGame.cleanTouch();
	}

	private void showOpenedIcon() {
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH && findViewById(R.id.isTablet) == null) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(false);
		}
		showMenu = false;
		supportInvalidateOptionsMenu();
		if (isSlideLock && mDrawerLayout != null)
			mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		actionBarSubtitle = getSupportActionBar().getSubtitle().toString();
		getSupportActionBar().setSubtitle(" ");
		if (mDrawerToggle != null)
			mDrawerToggle.syncState();
		currentGame.cleanTouch();
	}

	private void closeDrawer() {
		if (mDrawerLayout != null)
			mDrawerLayout.closeDrawers();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menuItemSmallTouch = menu.add(0, MENU_QUICK_TOUCH, 0, R.string.s49).setIcon(R.drawable.ic_action_smalltouch);
		menuItemSmallTouch.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		menuItemDeconnection = menu.add(0, MENU_DECONNECT, 0, R.string.s41).setVisible(getGamesClient().isConnected());
		openRightDrawer = menu.add(0, MENU_RIGHT_DRAWER, 0, R.string.s70);
		openRightDrawer.setVisible(findViewById(R.id.isTablet) == null && isSlideLock);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.findItem(MENU_QUICK_TOUCH).setVisible(showMenu);
		menu.findItem(MENU_RIGHT_DRAWER).setVisible(findViewById(R.id.isTablet) == null && showMenu && isSlideLock);

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case android.R.id.home:

			if (mDrawerLayout.isDrawerOpen(rightDrawer))
				mDrawerLayout.closeDrawer(rightDrawer);
			else
				mDrawerToggle.onOptionsItemSelected(Tools.getMenuItem(item));

			return true;
		case MENU_RIGHT_DRAWER:
			if (mDrawerLayout != null) {
				mDrawerLayout.openDrawer(rightDrawer);
			}
			break;
		case MENU_QUICK_TOUCH:
			currentGame.activateQuickTouchMode();

			nextIconForSmallTouchMenu = nextIconForSmallTouchMenu == R.drawable.ic_action_smalltouch_disactivate ? R.drawable.ic_action_smalltouch : R.drawable.ic_action_smalltouch_disactivate;
			menuItemSmallTouch.setIcon(nextIconForSmallTouchMenu);
			menuItemSmallTouch.setTitle(nextIconForSmallTouchMenu == R.drawable.ic_action_smalltouch_disactivate ? R.string.s50 : R.string.s49);

			if (nextIconForSmallTouchMenu == R.drawable.ic_action_smalltouch_disactivate)
				initHelpPopup(true);
			else
				initHelpPopup(false);

			return true;
		case MENU_DECONNECT:
			signOut();
			onSignInFailed();
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		if (mDrawerToggle != null)
			mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		if (mDrawerToggle != null)
			mDrawerToggle.onConfigurationChanged(newConfig);
		nextIconForSmallTouchMenu = R.drawable.ic_action_smalltouch;
		menuItemSmallTouch.setIcon(nextIconForSmallTouchMenu);
		menuItemSmallTouch.setTitle(R.string.s49);
		currentGame.resetQuickTouchZone();
		getSupportActionBar().setSubtitle("");
	}

	@Override
	protected void onPause() {
		allGames.set(currentGameIndex, currentGame.saveGameAsString());
		DataManager.SaveAllGames(allGames, getApplicationContext());
		super.onPause();
	}

	@SuppressLint("InlinedApi")
	@Override
	protected void onResume() {
		allGames = DataManager.GetAllSavedGames(getApplicationContext());
		adapter.notifyDataSetChanged();
		if (allGames.size() == 0) {
			currentGame.createNewGame();
			allGames.add(0, currentGame.saveGameAsString());
		} else {
			currentGame.launchGame(allGames.get(0));
		}

		// change the default blue scroll glow
		int glowDrawableId = getApplicationContext().getResources().getIdentifier("overscroll_glow", "drawable", "android");
		if (glowDrawableId > 0) {
			Drawable androidGlow = getApplicationContext().getResources().getDrawable(glowDrawableId);
			androidGlow.setColorFilter(Color.parseColor(getString(R.color.ui_color)), PorterDuff.Mode.SRC_ATOP);
		}

		// change the default blue scroll edge
		int edgeDrawableId = getApplicationContext().getResources().getIdentifier("overscroll_edge", "drawable", "android");
		if (edgeDrawableId > 0) {
			Drawable androidEdge = getApplicationContext().getResources().getDrawable(edgeDrawableId);
			androidEdge.setColorFilter(Color.parseColor(getString(R.color.ui_color)), PorterDuff.Mode.SRC_ATOP);
		}

		Drawable home = null;
		if (((ImageView) findViewById(android.R.id.home)) != null)
			home = ((ImageView) findViewById(android.R.id.home)).getDrawable();
		if (home == null)
			home = ((ImageView) findViewById(R.id.abs__home)).getDrawable();
		home.setAlpha(255);

		super.onResume();
	}

	@Override
	protected void onActivityResult(int request, int response, Intent data) {

		switch (request) {
		case RESULT_CONGRATS:
			restartGame();
			break;
		case RESULT_ACHIVEMENTS:
		case RESULT_LEADERBOARDS:
			if (allGames.size() == 0) {
				currentGame.createNewGame();
				allGames.add(0, currentGame.saveGameAsString());
			} else {
				currentGame.launchGame(allGames.get(0));
			}
			break;
		default:
			break;
		}

		super.onActivityResult(request, response, data);
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	@Override
	public void onSignInFailed() {
		findViewById(R.id.sign_in_panel).setVisibility(View.VISIBLE);
		if (menuItemDeconnection != null)
			menuItemDeconnection.setVisible(false);
		LinearLayout c = (LinearLayout) findViewById(R.id.container_play);
		c.setBackgroundDrawable(getResources().getDrawable(R.drawable.ab_background_textured_hanoi));
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
			c.setAlpha(0.7f);
		}

		((LinearLayout) findViewById(R.id.btn_achievement)).setBackgroundResource(0);
		((LinearLayout) findViewById(R.id.btn_leaderboard)).setBackgroundResource(0);

		((TextView) findViewById(R.id.tvLeaderboards)).setTextColor(getResources().getColor(R.color.signinTextOverlay));
		((TextView) findViewById(R.id.tvAchievements)).setTextColor(getResources().getColor(R.color.signinTextOverlay));
	}

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	@Override
	public void onSignInSucceeded() {
		findViewById(R.id.sign_in_panel).setVisibility(View.GONE);
		if (menuItemDeconnection != null)
			menuItemDeconnection.setVisible(true);

		LinearLayout c = (LinearLayout) findViewById(R.id.container_play);
		c.setBackgroundDrawable(null);
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
			c.setAlpha(1);
		}

		((LinearLayout) findViewById(R.id.btn_achievement)).setBackgroundResource(R.drawable.list_selector_holo_light_big);
		((LinearLayout) findViewById(R.id.btn_leaderboard)).setBackgroundResource(R.drawable.list_selector_holo_light_big);

		((TextView) findViewById(R.id.tvLeaderboards)).setTextColor(getResources().getColor(R.color.signinTextNoOverlay));
		((TextView) findViewById(R.id.tvAchievements)).setTextColor(getResources().getColor(R.color.signinTextNoOverlay));
	}

	static Handler handler = new Handler();

	@Override
	public void turnPlayed(final int nbCoup, int nbTotal) {
		actionBarSubtitle = nbCoup + " / " + nbTotal;
		getSupportActionBar().setSubtitle(actionBarSubtitle);
		if (isSignedIn()) {
			if (2147483647 == nbTotal) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_are_you_crazy_));
			}
		}
	}

	@Override
	public void gameFinished(int nbCoup, int nbTotal, long miliseconds) {
		if (isSignedIn()) {
			getGamesClient().incrementAchievement(getString(R.string.achievement_beginner), (int) (Math.log(nbCoup + 1) / Math.log(2)));
			getGamesClient().incrementAchievement(getString(R.string.achievement_expert), (int) (Math.log(nbCoup + 1) / Math.log(2)));
			if (nbTotal == 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_1));
			} else if (nbTotal == Math.pow(2, 2) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_2));
			} else if (nbTotal == Math.pow(2, 3) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_3));
			} else if (nbTotal == Math.pow(2, 4) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_4));
			} else if (nbTotal == Math.pow(2, 5) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_5));
				if (nbCoup == Math.pow(2, 5) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_5));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_5_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 6) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_6));
				if (nbCoup == Math.pow(2, 6) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_6));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_6_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 7) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_7));
				if (nbCoup == Math.pow(2, 7) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_7));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_7_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 8) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_8));
				if (nbCoup == Math.pow(2, 8) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_8));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_8_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 9) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_9));
				if (nbCoup == Math.pow(2, 9) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_9));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_9_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 10) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_10));
				if (nbCoup == Math.pow(2, 10) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_10));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_10_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 11) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_11));
				if (nbCoup == Math.pow(2, 11) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_11));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_11_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 12) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_12));
				if (nbCoup == Math.pow(2, 12) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_12));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_12_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 13) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_13));
				if (nbCoup == Math.pow(2, 13) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_13));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_13_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 14) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_14));
				if (nbCoup == Math.pow(2, 14) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_14));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_14_disks), miliseconds);
			} else if (nbTotal == Math.pow(2, 15) - 1) {
				getGamesClient().unlockAchievement(getString(R.string.achievement_level_15));
				if (nbCoup == Math.pow(2, 15) - 1)
					getGamesClient().unlockAchievement(getString(R.string.achievement_perfect_15));
				getGamesClient().submitScore(getString(R.string.leaderboard_fastest_for_15_disks), miliseconds);
			}

			if (nbTotal == nbCoup) {
				getGamesClient().submitScore(getString(R.string.leaderboard_perfect_score), (int) (Math.log(nbCoup + 1) / Math.log(2)));
			}
		}

		Intent i = new Intent(this, CongratsActivity.class);
		Bundle b = new Bundle();
		b.putInt("userMovements", nbCoup);
		b.putInt("totalMovements", nbTotal);
		b.putLong("time", miliseconds);
		i.putExtras(b);
		startActivityForResult(i, RESULT_CONGRATS);
	}

	public void restartGame() {
		String s = currentGame.saveGameAsString();
		allGames.set(currentGameIndex, s);
		currentGame.createNewGame();
		String s2 = currentGame.saveGameAsString();
		allGames.add(0, s2);
		DataManager.SaveAllGames(allGames, getApplicationContext());
		allGames = DataManager.GetAllSavedGames(getApplicationContext());

		nextIconForSmallTouchMenu = R.drawable.ic_action_smalltouch;
		menuItemSmallTouch.setIcon(nextIconForSmallTouchMenu);
		menuItemSmallTouch.setTitle(R.string.s49);
		currentGame.resetQuickTouchZone();
		adapter.notifyDataSetChanged();
	}

	public void showTutorial() {
		Intent i = new Intent(MainActivity.this, TutoActivity.class);
		startActivity(i);
		overridePendingTransition(0, 0);
		closeDrawer();
	}

	class GameAdapter extends BaseAdapter {
		LayoutInflater inflater;

		public GameAdapter(LayoutInflater inflater) {
			this.inflater = inflater;
		}

		@Override
		public int getCount() {
			return allGames.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		@Override
		public View getView(int pos, View convertView, ViewGroup parent) {
			View v = convertView;

			if (v == null)
				v = inflater.inflate(R.layout.template_game, null);

			GameView gv = (GameView) v.findViewById(R.id.gv);
			gv.launchGame(allGames.get(pos));
			gv.setDisabled(true);

			v.findViewById(R.id.iv_playing).setVisibility(pos == currentGameIndex ? View.VISIBLE : View.INVISIBLE);
			v.findViewById(R.id.clickableArea).setBackgroundResource(pos == currentGameIndex ? R.drawable.list_selector_background_transition_holo_light : R.drawable.list_selector_holo_light);

			TextView tvSectionTitle = (TextView) v.findViewById(R.id.tv_sectionTitle);
			if (pos == 0) {
				tvSectionTitle.setText(R.string.s72);
				tvSectionTitle.setVisibility(View.VISIBLE);
			} else if (pos == 1) {
				tvSectionTitle.setText(R.string.s73);
				tvSectionTitle.setVisibility(View.VISIBLE);
			} else {
				tvSectionTitle.setVisibility(View.GONE);
			}

			tvSectionTitle.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

				}
			});

			final int position = pos;
			v.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (position != currentGameIndex) {
						allGames.set(currentGameIndex, currentGame.saveGameAsString());
						String newGame = allGames.get(position);
						allGames.remove(position);
						allGames.add(0, newGame);
						currentGame.launchGame(allGames.get(currentGameIndex));
						adapter.notifyDataSetChanged();
						closeDrawer();
						lv.smoothScrollToPosition(currentGameIndex);
					}
				}
			});

			ImageView ivPopup = (ImageView) v.findViewById(R.id.iv_popup);
			ivPopup.setVisibility(position != 0 ? View.VISIBLE : View.GONE);

			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
				ivPopup.setOnClickListener(new OnClickListener() {

					@SuppressLint("NewApi")
					@Override
					public void onClick(View v) {
						PopupMenu menu = new PopupMenu(MainActivity.this, v);
						menu.getMenuInflater().inflate(R.menu.popup_save, menu.getMenu());
						menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

							@Override
							public boolean onMenuItemClick(android.view.MenuItem item) {

								switch (item.getItemId()) {
								case R.id.menu_delete:
									allGames.remove(position);
									notifyDataSetChanged();
									break;
								default:
									break;
								}
								return true;
							}
						});
						menu.show();
					}
				});
			} else {
				ivPopup.setImageResource(R.drawable.ic_content_discard);
				ivPopup.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						allGames.remove(position);
						notifyDataSetChanged();
					}
				});
			}

			return v;
		}

	}

}
